#!/usr/bin/env bash
#
# Copyright (c) 2020-2023 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

JQ=$(which jq)
if [ $? -ne 0 ]; then
    echo "'jq' not detected in PATH. Install using: brew install jq"
    exit 1
fi

set -e
set -x

source "$(dirname "$0")/../../scripts/activate.sh"
CHIP_ROOT="$(dirname "$0")/../.."
OUTPUT_DIR=$2

# Build the framework
scripts/examples/gn_build_example.sh "$@" generate_compilation_database=true

# Clean up any stale DB files
find "$OUTPUT_DIR" -iname compile_commands\*.json | xargs rm

# Construct json from fragments generated by xcodebuild
COMPDB_FRAGMENTS_DIR=$(find "$OUTPUT_DIR" -type d -name compdb)
sed -e '1s/^/[\'$'\n''/' -e '$s/,$/\'$'\n'']/' "$COMPDB_FRAGMENTS_DIR"/*.json >"$OUTPUT_DIR"/compile_commands_darwin_framework.json

# Get ninja to build comdb for the rest
ninja -C "$OUTPUT_DIR" -t compdb >"$OUTPUT_DIR"/compile_commands_rest.json

# Combine the generated compdb into one
find "$OUTPUT_DIR" -iname compile_commands\*.json | xargs jq -s 'map(.[])' >"$OUTPUT_DIR"/compile_commands.json
